package com.panku.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.panku.util.XMLBean;
/**
 * 该servlet用来作为核心控制器，主要将请求和对应的处理类进行配对，并把结果返回给对应的页面
 * @author jack
 *
 */
public class DispatcherController extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setCharacterEncoding("utf-8");
		req.setCharacterEncoding("utf-8");
		String path = getPath(req.getServletPath());
		System.out.println(path);
		Map<String, XMLBean> resultMap=(Map<String, XMLBean>)req.getServletContext().getAttribute("actions");
		XMLBean nowBean=resultMap.get(path);
		Class clazz=null;
		String forwardName="";
		String methodName=nowBean.getMethod()==null?"execute":nowBean.getMethod();
		try {
			//调用指定方法
			clazz = Class.forName(nowBean.getActionClass());
			Method actionMethod = clazz.getDeclaredMethod(methodName, HttpServletRequest.class);
			Object methodRes = actionMethod.invoke(clazz.newInstance(),req);
			if (methodRes!=null) {
				forwardName = methodRes.toString();
			}
			//调用默认方法
//			BaseController action =(BaseController) clazz.newInstance();
//			forwardName=action.execute(req);
			req.getRequestDispatcher(nowBean.getForward().get(forwardName)).forward(req, resp);
			System.out.println("执行完程序后的返回值是:"+forwardName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		/*PrintWriter out=resp.getWriter();
		out.print("哈哈");*/
	}
	
	public String getPath(String sourceStr){
		if (sourceStr!=null&&sourceStr.length()>0) {
			return sourceStr.split("\\.")[0];
		}
		return null;
	}
	

}
